<template>
    <div>
        <el-row :gutter="20">
            <el-col :span="6">
                <el-input type="text" id="uname" v-model="formName.uname" placeholder="请输入账号">
                    <template slot="prepend">帐号</template>
                </el-input>
            </el-col>
            <el-col :span="6">
                <el-input type="text" id="umobile" v-model="formName.umobile" placeholder="请输入手机号">
                    <template slot="prepend">手机号</template>
                </el-input>
            </el-col>
        </el-row>
        <el-row :gutter="20">
            <el-col :span="30">
                <el-date-picker v-model="formName.insertTimeStart" value-format="yyyy-MM-dd" type="date"
                                placeholder="选择开始日期"></el-date-picker>
                <label>-</label>
                <el-date-picker v-model="formName.insertTimeEnd" value-format="yyyy-MM-dd" type="date"
                                placeholder="选择结束日期"></el-date-picker>
            </el-col>
            <el-col :span="3.5">
                <el-button @click="resetForm">重置</el-button>
                <el-button type="primary" @click="submitForm">提交</el-button>
            </el-col>
            <!--<el-col :span="6">-->
            <!--<p style="float: left;color: red">{{formName.error}}</p>-->
            <!--</el-col>-->
        </el-row>
        <hr/>
        <el-row :gutter="20">
            <el-col :span="10">
                <el-button type="success" @click="addUser">开通用户</el-button>
            </el-col>
        </el-row>
        <el-table :data="tableData" border style="width: 100%">
            <el-table-column type="index" label="NO" width="50"></el-table-column>
            <el-table-column prop="username" label="用户名" width="150"></el-table-column>
            <el-table-column prop="mobile" label="手机号" width="200"></el-table-column>
            <el-table-column prop="email" label="邮箱地址" width="200"></el-table-column>
            <el-table-column prop="roleNames" label="角色名称"></el-table-column>
            <el-table-column prop="insertTime" label="添加时间" width="200"></el-table-column>
            <el-table-column label="是否在职" width="100">
                <!--<el-radio-group v-model="currentLine.job">-->
                <!--<el-radio>测试</el-radio>-->
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.job"
                               active-color="#13ce66"
                               inactive-color="#ff4949"
                               @change="changeSwitch(scope.row)">
                    </el-switch>
                    <!--<el-button type="text" size="small">编辑</el-button>-->
                    <!--<el-radio-group v-model="radio3">-->
                    <!--<el-radio-button label="true">男</el-radio-button>-->
                    <!--&lt;!&ndash;<el-radio-button label="false">女</el-radio-button>&ndash;&gt;-->
                    <!--</el-radio-group>-->
                </template>
                <!--</el-radio-group>-->
            </el-table-column>
            <el-table-column label="操作" width="150">
                <template slot-scope="scope">
                    <el-button @click="editor(scope.row)" type="primary" icon="el-icon-edit" size="small"></el-button>
                    <el-button @click="del(scope.row)" type="danger" icon="el-icon-delete" size="small"></el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination v-if="this.formName.total > 0" style="float: right;padding-top: 10px"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       :current-page=this.formName.page
                       :page-sizes="[2, 3, 40,100]"
                       :page-size=this.formName.limit
                       layout="total, sizes, prev, pager, next, jumper"
                       :total=this.formName.total>
        </el-pagination>
        <el-dialog :title=dialogTitle :visible.sync="dialogFormVisible">
            <el-row>
                <el-col>
                    <el-input type="text" id="dUsername" v-model="dialogForm.username"
                              :disabled="dialogForm.unameIsdisabled" placeholder="请输入账号"
                              @blur="inputBlur('user',dialogForm.username)">>
                        <template slot="prepend">帐号</template>
                    </el-input>
                </el-col>
            </el-row>
            <el-row :gutter="10">
                <el-col>
                    <el-input type="text" id="dPassword" v-model="dialogForm.password" placeholder="请输入密码">
                        <template slot="prepend">密码</template>
                    </el-input>
                </el-col>
            </el-row>
            <el-row :gutter="10">
                <el-col>
                    <el-input type="text" id="dEmail" v-model="dialogForm.email" placeholder="请输入邮箱"
                              @blur="inputBlur('email',dialogForm.email)">
                        <template slot="prepend">邮箱</template>
                    </el-input>
                </el-col>
            </el-row>
            <el-row :gutter="10">
                <el-col>
                    <el-input type="text" id="dMobile" v-model="dialogForm.mobile" placeholder="请输入手机号"
                              @blur="inputBlur('mobile',dialogForm.mobile)">
                        <template slot="prepend">手机号</template>
                    </el-input>
                </el-col>
            </el-row>
            <el-row :gutter="10">
                <el-col :span="10">
                    <label>授予角色</label>
                </el-col>
            </el-row>
            <el-row :gutter="10">
                <el-col>
                    <el-checkbox-group v-model="dialogForm.checkList">
                        <el-checkbox v-for="item in dialogCheckboxData" :label="item.id">{{item.roleName}}</el-checkbox>
                    </el-checkbox-group>
                </el-col>
            </el-row>
            <el-row :gutter="10">
                <el-col :span="10">
                    <el-button type="primary" @click="dialogSubmitForm">提交</el-button>
                    <el-button @click="dialogResetForm">重置</el-button>
                    <p>{{error.msg}}</p>
                </el-col>
            </el-row>
        </el-dialog>
    </div>
</template>

<script type="text/ecmascript-6">
    export default {
        data() {
            return {
                error: {
                    msg: ''
                },
                dialogForm: {//新增参数
                    id:'',
                    username: '',
                    unameIsdisabled: false,
                    mobile: '',
                    email: '',
                    password: '',
                    checkList: [],
                    typeStr: "",
                    roleIds: ""
                },
                formName: {//表单中的参数
                    uname: '',
                    umobile: '',
                    insertTimeStart: '',
                    insertTimeEnd: '',
                    error: "",
                    page: 1,
                    limit: 2,
                    total: ''
                },
                tableData: [],
                total: 0,
                radio3: "true",
                dialogFormVisible: false,
                dialogTitle: "",
                dialogCheckboxData: "",
                dialogAddTitleStr: "新增用户",
                dialogUpdateTitleStr: "修改用户",

            }
        },
        mounted() {
            this.submitForm();
        },
        methods: {
            changeSwitch: function (row) {
                var jobInt = 0;
                if (row.job) {
                    jobInt = 1;
                } else {
                    jobInt = 0;
                }
                // this.$alert(row.job);
                var params = "";
                params += "?id=" + row.id;
                params += "&job=" + jobInt;
                params += "&version=" + row.version;
                this.$axios.post(this.$serverUrl + '/user/setJobUser' + params).then((res) => {
                    console.log(res);
                }).catch((res) => {
                    this.$alert(res.response.data.response.msg);
                })
            },
            resetForm: function () {
                this.formName.page = "1";
                this.formName.limit = "2";
                this.formName.uname = "";
                this.formName.umobile = "";
                this.formName.insertTimeStart = "";
                this.formName.insertTimeEnd = "";
                this.submitForm();
            },
            submitForm: function () {
                var params = "";
                params += "?page=" + this.formName.page;
                params += "&limit=" + this.formName.limit;
                params += "&uname=" + this.formName.uname;
                params += "&umobile=" + this.formName.umobile;
                if (this.formName.insertTimeStart != null) {
                    params += "&insertTimeStart=" + this.formName.insertTimeStart;
                }
                if (this.formName.insertTimeEnd != null) {
                    params += "&insertTimeEnd=" + this.formName.insertTimeEnd;
                }
                this.$axios.get(this.$serverUrl + '/user/getUsers' + params).then((res) => {
                    console.log(res.data.list);
                    this.tableData = res.data.list;
                    this.formName.total = res.data.totals;
                }).catch((res) => {
                    this.$alert(res.response.data.response.msg);
                })
            },
            handleSizeChange: function (val) {
                this.formName.limit = val;
                this.submitForm();
            },
            handleCurrentChange(val) {
                this.formName.page = val;
                this.submitForm();
            },
            clearDialogForm: function () {
                this.dialogForm.username = "";
                this.dialogForm.password = "";
                this.dialogForm.email = "";
                this.dialogForm.mobile = "";
                this.error.msg = "";
            },
            // 开通用户
            addUser: function () {
                this.dialogTitle = this.dialogAddTitleStr;
                this.clearDialogForm(); // 清除数据
                this.dialogForm.unameIsdisabled = false;// 是否可编辑
                this.dialogFormVisible = true;
                this.getAllRoles();// 获取所有角色

            },// 编辑用户
            editor: function (row) {
                this.dialogTitle = this.dialogUpdateTitleStr;
                this.dialogForm.id = row.id;
                this.dialogForm.username = row.username;
                this.dialogForm.email = row.email;
                this.dialogForm.mobile = row.mobile;
                this.dialogForm.unameIsdisabled = true;
                this.getUserAndRoles(row.id);
                this.dialogFormVisible = true;
            },
            del: function (row) {
                var msg = "是否删除用户[" + row.username + "]？";
                this.$confirm(msg, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.doDel(row);
                    this.submitForm();
                }).catch(() => {
                });
            },
            doDel:function(row){
                var params = "";
                params += "?id=" + row.id;
                params += "&version=" + row.version;
                this.$axios.post(this.$serverUrl + '/user/delUser' + params).then((res) => {
                    console.log(res.data);
                }).catch((res) => {
                    console.log(res.data);
                })
            },
            checkRole: function () {
                //选中的角色
                var array = new Array();
                var roleCheckd = this.dialogForm.checkList;

                //校验是否授权
                var roleIds = roleCheckd.join(",");
                if (roleIds == null || roleIds == '') {
                    this.error.msg = "请您给该用户添加对应的角色！";
                    return false;
                }
                this.dialogForm.roleIds = roleIds;
                return true;
            },
            doSetUser: function () {
                if (this.error.msg != "") {
                    return false;
                }
                var isError = this.checkRole();
                if (!isError) {
                    return false;
                }
                var params = "";
                params += "?roleIds=" + this.dialogForm.roleIds;
                this.$axios(
                    {
                        contentType: 'application/json',
                        dataType: "json",
                        method: 'post',
                        url: this.$serverUrl + '/user/setUser' + params,
                        data: this.dialogForm
                    }
                ).then((res) => {
                    if (res.data.isSucess){
                        this.dialogFormVisible = false;
                        this.$alert(res.data.msg);
                        this.submitForm();// 查询
                    } else{
                        this.error.msg = res.data.msg;
                    }

                }).catch((res) => {
                    this.$alert(res.response.data.response.msg);
                });
                return true;
            },
            dialogSubmitForm: function () {
                // 更新/新增用户
                this.doSetUser();
            },
            dialogResetForm: function () {

            },
            getUserAndRoles: function (userId) {
                var params = "";
                params += "?id=" + userId;
                this.$axios.get(this.$serverUrl + '/user/getUserAndRoles' + params).then((res) => {
                    console.log(res.data);
                    this.setRoles(res.data.roles);
                    this.setRolesCheck(res.data.user.userRoles);
                }).catch((res) => {
                    console.log(res.data);
                })
            },
            getAllRoles: function () {
                this.$axios.get(this.$serverUrl + '/auth/getRoles').then((res) => {
                    console.log(res.data);
                    this.setRoles(res.data);
                }).catch((res) => {
                    console.log(res.data);
                })
            },
            setRoles: function (data) {
                this.dialogForm.checkList = [];
                this.dialogCheckboxData = data;
            },
            setRolesCheck: function (dataCheck) {
                for (let i = 0; i < dataCheck.length; i++) {
                    this.dialogForm.checkList.push(dataCheck[i].roleId);
                }
            },
            inputBlur: function (errorItem, inputContent) {
                if (errorItem === 'user') {
                    if (inputContent === '') {
                        this.error.msg = '用户名不能为空';
                    } else {
                        this.error.msg = '';
                    }
                } else if (errorItem === 'email') {
                    if (inputContent === '') {
                        this.error.msg = '邮件不能为空';
                    } else {
                        this.error.msg = '';
                    }
                } else if (errorItem === 'mobile') {
                    if (inputContent === '') {
                        this.error.msg = '手机不能为空';
                    } else {
                        this.error.msg = '';
                    }
                }
            }
        }
    }
</script>
<style scoped>
    .el-row {
        margin-bottom: 20px;
    }

    hr {
        height: 1px;
        margin: 10px 0;
        border: 0;
        background-color: #393D49 !important;
        clear: both;
    }

    p {
        color: red;
        text-align: left;
    }
</style>